(function () {

    const checkAll = document.getElementById('checkAll');
    const tbody = document.getElementsByTagName('tbody')[0];
    const checkOneList = tbody.getElementsByTagName('input');
    const ths = document.getElementsByTagName('th');
    const rows = tbody.getElementsByTagName('tr');


    let init = function () {
        initEvent();
    }

    let initEvent = function () {
        checkAll.addEventListener('click', handleCheckAll);
        tbody.addEventListener('click', handleCheckOneList);
        for (let i = 0; i < ths.length; i++) {
            handleThsClickFn(ths[i], i)
        }
    }

    let handleCheckAll = function () {
        let checkAllStatus = checkAll.checked;
        for (let i = 0; i < checkOneList.length; i++) {
            checkOneList[i].checked = checkAllStatus
        }
    }

    let handleCheckOneList = function (e) {
        if (e.target.tagName !== 'INPUT') return;
        let checkNumber = 0;
        for (let i = 0; i < checkOneList.length; i++) {
            checkOneList[i].checked && checkNumber++;
        }
        checkAll.checked = (checkNumber === checkOneList.length);
    }

    let handleThsClickFn = function (th, index) {
        if (index === 0) return;
        th.addEventListener('click', function () {
            let arr = Array.prototype.slice.call(rows).sort((a, b) => {
                if (index === 2 || index === 4) {
                    return a.getElementsByTagName('td')[index].innerHTML.localeCompare(b.getElementsByTagName('td')[index].innerHTML);
                } else {
                    return a.getElementsByTagName('td')[index].innerHTML - b.getElementsByTagName('td')[index].innerHTML;
                }
            })
            for (let i = 0; i < arr.length; i++) {
                tbody.appendChild(arr[i]);
            }
        })
    }
    init()
})()